package saucaca.fragment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

import org.json.JSONException;

import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Util.AppController;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.media.RemoteControlClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.lemon.kenhnhacvn.BaseActivity;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

public class AccountLoginFragment extends Fragment {
	String TAG = AccountLoginFragment.class.getSimpleName();
	String Account="0";
	String Facebook="1";
	String Google="2";
	ImageLoader imageLoader;
	String type_login;
	private ProgressDialog progressDialog;
	private MainActivity mActivity = null;
	LinearLayout btnRegister, btnFacebook, btnGoogle, btnLogin;
	String user, pass,is3G=Account,token="";
	Resources resources;
	EditText edtUser, edtPass;

	boolean isFacebook = false;
	 private UiLifecycleHelper uiHelper;
	    
	AccountManager mAccountManager;
	
	int serverCode;
	private static final String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";
	String GOOGLE_USER_DATA;
	
	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.account_login, container, false);
		findViewById(view);
		resources = mActivity.getResources();
		mActivity.myActionBar.setMenu(R.string.login, false, false);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		String user=PreferenceUtils.getString(mActivity, TagName.KeyPreference_user);
		String facebook=PreferenceUtils.getString(mActivity, TagName.KeyPreference_typelogin);
		if(user==null)
			callFacebookLogout(mActivity);
		else{
			if(!facebook.equals(TagName.KeyPreference_facebook))
				callFacebookLogout(mActivity);
		}
	}
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if(!hidden)
			mActivity.myActionBar.setMenu(R.string.login, false, false);
	}

	public void findViewById(View view) {
		type_login=TagName.KeyPreference_facebook;
		btnRegister = (LinearLayout) view.findViewById(R.id.login_btnLinear_registerButton);
		btnLogin = (LinearLayout) view.findViewById(R.id.login_btnLinear_loginButton);
		btnFacebook = (LinearLayout) view.findViewById(R.id.login_btnLinear_loginFacebook);
		btnGoogle = (LinearLayout) view.findViewById(R.id.login_btnLinear_loginGoogle);
		edtUser = (EditText) view.findViewById(R.id.login_edt_username);
		edtPass = (EditText) view.findViewById(R.id.login_edt_password);

		btnRegister.setOnClickListener(clickListener);
		btnLogin.setOnClickListener(clickListener);
		btnFacebook.setOnClickListener(clickListener);
		btnGoogle.setOnClickListener(clickListener);
		LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(Arrays.asList( "public_profile","email", "user_status", "user_birthday"));
        progressDialog = new ProgressDialog(mActivity);
        edtUser.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm != null) {
					if (hasFocus) {
						imm.showSoftInput(edtUser, InputMethodManager.SHOW_IMPLICIT);
					} else
						imm.hideSoftInputFromWindow(edtUser.getWindowToken(), 0);
				}

			}
		});
		edtPass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm != null) {
					if (hasFocus) {
						imm.showSoftInput(edtPass, InputMethodManager.SHOW_IMPLICIT);
					} else
						imm.hideSoftInputFromWindow(edtPass.getWindowToken(), 0);
				}

			}
		});
	}
	/**
	 * Logout From Facebook 
	 */
	public static void callFacebookLogout(Context context) {
	    Session session = Session.getActiveSession();
	    if (session != null) {

	        if (!session.isClosed()) {
	            session.closeAndClearTokenInformation();
	            //clear your preferences if saved
	        }
	    } else {

	        session = new Session(context);
	        Session.setActiveSession(session);

	        session.closeAndClearTokenInformation();
	            //clear your preferences if saved

	    }

	}
	View.OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			isFacebook = false;
			switch (v.getId()) {
			case R.id.login_btnLinear_registerButton:
				mActivity.switchContent(AccountRegisterFragment.class.getName());
				break;
			case R.id.login_btnLinear_loginButton:
				type_login=TagName.KeyPreference_Account;
				Login(edtUser.getText().toString(),edtPass.getText().toString(),Account,"");
				break;
			case R.id.login_btnLinear_loginGoogle:
//				syncGoogleAccount();
				type_login=TagName.KeyPreference_google;
				Toast.makeText(mActivity, "Đang cập nhật!", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		}
	};
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        // To maintain FB Login session
	        uiHelper = new UiLifecycleHelper(getActivity(), callback);
	        uiHelper.onCreate(savedInstanceState);
	    }
	 // Called when session changes
	    private Session.StatusCallback callback = new Session.StatusCallback() {
	        @Override
	        public void call(Session session, SessionState state,
	                Exception exception) {
	            onSessionStateChange(session, state, exception);
	        }
	    };
	 
	    // When session is changed, this method is called from callback method
	    private void onSessionStateChange(Session session, SessionState state,
	            Exception exception) {
	         
	        if (state.isOpened()) {
	            Log.i(TAG, "Logged in...");
	            // make request to the /me API to get Graph user
	            TagName.showLogError(TAG, "Facebook Access Token: "+session.getAccessToken());
	            Login("fb", "fb", Facebook, session.getAccessToken());
//	            Request.newMeRequest(session, new Request.GraphUserCallback() {
//	 
//	                // callback after Graph API response with user
//	                // object
//	                @Override
//	                public void onCompleted(final GraphUser user, Response response) {
//	                    if (user != null) {
//	                    	// Set User name
//	                    	TagName.showLogError(TAG, "User: " + user);
//	                        TagName.showLogError(TAG, "Hello: " + user.getName());
//	                        String id=user.getProperty("id").toString();
//	                        TagName.showLogError(TAG, "Your Id: " + id);
//	                        TagName.showLogError(TAG, "Your Email: " +user.getProperty("email").toString());
////	                        ImageView user_picture;
////	                        userpicture=(ImageView)findViewById(R.id.userpicture);
//	                        URL img_value = null;
//	                        try {
//								img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
//								TagName.showLogError(TAG, "Your avatar: "+img_value);
//							} catch (MalformedURLException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
////	                        Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
////	                        userpicture.setImageBitmap(mIcon1);
////	                        ImageLoader.getInstance().loadImage(img_value.toString(), new SimpleImageLoadingListener() {
////	        					@Override
////	        					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
////	        						super.onLoadingComplete(imageUri, view, loadedImage);
//	                        PreferenceUtils.putString(mActivity, TagName.KeyPreference_fullname, user.getProperty("name").toString());
//							PreferenceUtils.putString(mActivity, TagName.KeyPreference_usercode, user.getProperty("id").toString());
//							PreferenceUtils.putString(mActivity, TagName.KeyPreference_sex, user.getProperty("gender").toString());
////							PreferenceUtils.putString(mActivity, TagName.KeyPreference_birthday, user.getProperty("birthday").toString());
//							PreferenceUtils.putString(mActivity, TagName.KeyPreference_user, user.getProperty("email").toString());
////							PreferenceUtils.putString(mActivity, TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
////							PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
//							PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, img_value.toString());
//							PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  TagName.KeyPreference_facebook);
//							try {
//								mActivity.menuFragment.changedLoginstatus(true);
//							} catch (Exception e) {
//								Intent i = mActivity.getBaseContext().getPackageManager().getLaunchIntentForPackage(mActivity.getBaseContext().getPackageName());
//								i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//								startActivity(i);
//							}
////							TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
////							mActivity.showprevousFragment();
//	        						mActivity.showprevousFragment();
////	        					}
////	        				});
//	                    }
//	                }
//	            }).executeAsync();
	        } else if (state.isClosed()) {
	            Log.i(TAG, "Logged out...");
	        }
	    }
	 
	    @Override
	    public void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	 
	        uiHelper.onActivityResult(requestCode, resultCode, data);
	        Log.i(TAG, "OnActivityResult...");
	    }
	 
	    @Override
	    public void onResume() {
	        super.onResume();
	        uiHelper.onResume();
	    }
	 
	    @Override
	    public void onPause() {
	        super.onPause();
	        uiHelper.onPause();
	    }
	 
	    @Override
	    public void onDestroy() {
	        super.onDestroy();
	        uiHelper.onDestroy();
	    }
	 
	    @Override
	    public void onSaveInstanceState(Bundle outState) {
	        super.onSaveInstanceState(outState);
	        uiHelper.onSaveInstanceState(outState);
	    }
	
	private void Login(String _user,String _pass,String is3G,String token) {
		user = _user;//edtUser.getText().toString();
		pass = _pass;//edtPass.getText().toString();
		this.is3G=is3G;
		this.token=token;
		new GetFromServices().execute("");
		if(user.equals("gg")){
		PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  TagName.KeyPreference_google);
		}else if(user.equals("fb")){
			PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  TagName.KeyPreference_facebook);	
		}else{
			PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  TagName.KeyPreference_Account);
		}
	}
	class GetFromServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... param) {
			String str = WServiceLib.login(user, pass,is3G,token);
//			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				BaseEngine.showLogformLongString(result);
				try {
					JsonReader.readHeader(result);
					JsonReader.loginReader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject.getCODE().equals("0")) {
//				ImageLoader.getInstance().loadImage(HomeData.homeAccount.getAVATAR(), new ImageLoadingListener() {
//					
//					@Override
//					public void onLoadingStarted(String arg0, View arg1) {
//					}
//					
//					@Override
//					public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, HomeData.homeAccount.getAVATAR());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, HomeData.homeAccount.getAVATAR());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  type_login);
//						mActivity.menuFragment.changedLoginstatus(true);
//						TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
//						mActivity.showprevousFragment();
//						
//					}
//					
//					@Override
//					public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(arg2));
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, HomeData.homeAccount.getAVATAR());
//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  type_login);
//						mActivity.menuFragment.changedLoginstatus(true);
//						TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
//						mActivity.showprevousFragment();
//						
//					}
//					
//					@Override
//					public void onLoadingCancelled(String arg0, View arg1) {
//						
//					}
//				});
				
				try {
					imageLoader=((BaseActivity)mActivity).imageLoader;
				} catch (Exception e) {
					imageLoader=AppController.getInstance().getImageLoader();
				}
				imageLoader.get(HomeData.homeAccount.getAVATAR(), new ImageLoader.ImageListener() {
			        @Override
			        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
			        	Bitmap	arg2=response.getBitmap();
			        	
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(arg2));
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, HomeData.homeAccount.getAVATAR());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  type_login);
						mActivity.menuFragment.changedLoginstatus(true);
						TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
						mActivity.showprevousFragment();
			        	
			        }

					@Override
					public void onErrorResponse(VolleyError arg0) {
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, HomeData.homeAccount.getAVATAR());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar_url, HomeData.homeAccount.getAVATAR());
						PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  type_login);
						mActivity.menuFragment.changedLoginstatus(true);
						TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
						mActivity.showprevousFragment();
					}
			    });
			} else
				TagName.showToastShort(mActivity, HomeData.headerObject.getMESSAGE());
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mActivity = (MainActivity) activity;
		}
	}

	// Google ...
	private String[] getAccountNames() {
		mAccountManager = AccountManager.get(mActivity);
		Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
		}
		return names;
	}

	// Google ...
	public void syncGoogleAccount() {
		if(!progressDialog.isShowing()){
			progressDialog.show();
			if (BaseEngine.isConnectionAvailable(mActivity)== true) {
				String[] accountarrs = getAccountNames();
				if (accountarrs.length > 0) {
					// you can set here account for login
					new GetGoogleAccount(mActivity, accountarrs[0], SCOPE).execute();
				} else {
					Toast.makeText(mActivity, "No Google Account Sync!", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(mActivity, getResources().getString(R.string.error_connected), Toast.LENGTH_SHORT).show();
			}
		}
	}

	class GetGoogleAccount extends AsyncTask<Void, Void, Void> {
		protected MainActivity mActivity;
		protected String mScope;
		protected String mEmail;
		String TAG = "TokenInfoTask";

		GetGoogleAccount(MainActivity activity, String email, String scope) {
			this.mActivity = activity;
			this.mScope = scope;
			this.mEmail = email;
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				fetchNameFromProfileServer(mActivity, mEmail, mScope);
			} catch (IOException ex) {
				onError("Following Error occured, please try again. " + ex.getMessage(), ex);
			} catch (JSONException e) {
				onError("Bad response: " + e.getMessage(), e);
			}
			return null;
		}

		private void fetchNameFromProfileServer(final MainActivity mActivity, final String mEmail, String mScope) throws IOException, JSONException {
			String token = fetchToken(mActivity, mEmail, mScope);
			URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			Log.e(TAG,"Google Token:" + token);
			if (token!=null&&!token.equals("")) {
				Login("gp", "gp", Google, token);
			}
//			int sc = con.getResponseCode();
//			if (sc == 200) {
//				InputStream is = con.getInputStream();
//				GOOGLE_USER_DATA = readResponse(is);
//				try {
//					Log.e(TAG,"On Home Page***" + GOOGLE_USER_DATA);
//					final JSONObject profileData = new JSONObject( GOOGLE_USER_DATA);
//					String userImageUrl=null;
//					if (profileData.has("picture")) {
//						userImageUrl = profileData.getString("picture");
//					}
//					 ImageLoader.getInstance().loadImage(userImageUrl, new SimpleImageLoadingListener() {
//	 					@Override
//	 					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//	 						super.onLoadingComplete(imageUri, view, loadedImage);
//		                     try {
//		                    	 PreferenceUtils.putString(mActivity, TagName.KeyPreference_fullname, profileData.getString("name"));
//									PreferenceUtils.putString(mActivity, TagName.KeyPreference_usercode, profileData.getString("id"));
//									PreferenceUtils.putString(mActivity, TagName.KeyPreference_sex,  profileData.getString("gender"));
//			//						PreferenceUtils.putString(mActivity, TagName.KeyPreference_birthday, user.getProperty("birthday").toString());
//									PreferenceUtils.putString(mActivity, TagName.KeyPreference_user, mEmail);
//									PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
//									PreferenceUtils.putString(mActivity, TagName.KeyPreference_typelogin,  TagName.KeyPreference_google);
//		                    	 mActivity.runOnUiThread(new Runnable() {
//									@Override
//									public void run() {
//										if(progressDialog.isShowing())
//											progressDialog.hide();
//										mActivity.menuFragment.changedLoginstatus(true);
//										mActivity.showprevousFragment();
//									}
//								});
//								
//							} catch (JSONException e) {
//								e.printStackTrace();
//							}
//	 					}
//	 				});
//
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				is.close();
//				return;
//			} else if (sc == 401) {
//				GoogleAuthUtil.invalidateToken(mActivity, token);
//				onError("Server auth error, please try again.", null);
//				return;
//			} else {
//				onError("Server returned the following error code: " + sc, null);
//				return;
//			}
		}

		private String readResponse(InputStream is) throws IOException {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] data = new byte[2048];
			int len = 0;
			while ((len = is.read(data, 0, data.length)) >= 0) {
				bos.write(data, 0, len);
			}
			return new String(bos.toByteArray(), "UTF-8");
		}

		protected void onError(String msg, Exception e) {
			if (e != null) {
				Log.e(TAG, "Exception: ", e);
			}
		}

		int mRequestCode;

		protected String fetchToken(MainActivity mActivity, String mEmail, String mScope) throws IOException {
			try {
				return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
			} catch (GooglePlayServicesAvailabilityException playEx) {
			} catch (UserRecoverableAuthException userRecoverableException) {
				mActivity.startActivityForResult(userRecoverableException.getIntent(), mRequestCode);
			} catch (GoogleAuthException fatalException) {
				onError("Unrecoverable error " + fatalException.getMessage(), fatalException);
			}
			return null;
		}
	}

}
